#include "connection.hpp"
#include "event_loop.hpp"

using namespace event_framework;


void Connection::Open(const EventCallback& callback)
{
    if (callback.readableCallback)
    {
        auto&& func = callback.readableCallback;
        channel->ConcernReadableEvent([this, func]()->void
        {
           func(socket);
        });
    }
    if (callback.writeableCallback)
    {
        auto&& func = callback.writeableCallback;
        channel->ConcernWriteableEvent([this, func]()->void
        {
            func(socket);
        });
    }
    if (callback.exceptionCallback)
    {
        auto&& func = callback.exceptionCallback;
        channel->ConcernExceptionEvent([this, func](int err)->void
        {
            func(socket, err);
        });
    }
    if (callback.closedCallback)
    {
        auto&& func = callback.closedCallback;
        channel->ConcernClosedEvent([this, func]()->void
        {
            func(socket);
        });
    }
}

ConnectionPtr ConnectionMgr::GetConnection(int fd)
{
    if (connMap.count(fd) == 0)
    {
        return nullptr;
    }
    return connMap.at(fd);
}
void ConnectionMgr::CloseConnection(int fd)
{
    if (connMap.count(fd) > 0)
    {
        auto conn = connMap.at(fd);
        conn->Close();
        connMap.erase(fd);
    }
}
void ConnectionMgr::CloseAll()
{
    for (const auto& kv : connMap)
    {
        ASSERT(kv.second != nullptr);
        kv.second->Close();
    }
    connMap.clear();
}